package cn.restcloud.example.controller.login;

import cn.restcloud.apiportal.dao.IApiPortalCallAppyDao;
import cn.restcloud.apiportal.dao.IApiProtalApiConfigDao;
import cn.restcloud.apiportal.model.P_ApiProtalCallAppyEntry;
import org.bson.Document;
import cn.restcloud.framework.core.annotation.bean.BeanConfig;
import cn.restcloud.framework.core.annotation.bean.BeanType;
import cn.restcloud.framework.core.annotation.rest.Param;
import cn.restcloud.framework.core.annotation.rest.Params;
import cn.restcloud.framework.core.annotation.rest.RestConfig;
import cn.restcloud.framework.core.context.AppContext;
import cn.restcloud.framework.core.util.RequestUtil;
import cn.restcloud.framework.view.base.DocAndView;
import cn.restcloud.framework.view.util.ViewUtil;

/**
 * apiportal API 调用申请、审批服务
 * @author Administrator
 *
 */
@BeanConfig(appId = "apiportal",beanId = "ApiApproverRest",beanName = "API审批权限集成示例",beanType = BeanType.CONTROLLER,autowired = true,singleton = true,hotMode = true)
@RestConfig(url = "/rest/apiportal/approver")
public class ApiApproverRest {
	
	private IApiPortalCallAppyDao dao;
	private IApiProtalApiConfigDao apiConfigDao;

	@RestConfig(configName = "根据ids删除审批记录",method = "POST",url = "/delete")
	@Params({ 
		@Param(id = "ids", name = "唯一id多个逗号分隔",required=true)
	})
	public DocAndView deleteAppsById()throws Exception{
		String ids=RequestUtil.getString("ids");
		int r=dao.deleteByIds(ids);//根据id进行删除
		return ViewUtil.getSuccessView(r);
	}
	
	@RestConfig(configName = "申请调用API",method = "POST",url = "/agree")
	@Params({ 
		@Param(id = "apiId", name = "申请API的唯一22位id",required=true),
		@Param(id = "remark", name = "申请理由",required=false)
	})
	public DocAndView save(String apiId,String remark)throws Exception{
		Document apiDoc=apiConfigDao.getById(apiId);
		if(apiDoc==null) {return ViewUtil.getErrorView("API不存在!");}
		
		//检测是否已经申请过了
		P_ApiProtalCallAppyEntry oldAppy=dao.getByApiId(apiId, AppContext.getUserId(),0); //审批中的
		if(oldAppy!=null) {return ViewUtil.getErrorView("本API您已经申请过了,等待("+oldAppy.getApproverUserId()+")审批!");}
		
		oldAppy=dao.getByApiId(apiId, AppContext.getUserId(),1); //已通过的
		if(oldAppy!=null) {return ViewUtil.getErrorView("本API您已经申请过了,且已经审批通过!");}
		
		P_ApiProtalCallAppyEntry apiProtalCallAppyEntry=new P_ApiProtalCallAppyEntry();
		apiProtalCallAppyEntry.setAppId(apiDoc.getString("appId"));
		apiProtalCallAppyEntry.setApiId(apiId);
		apiProtalCallAppyEntry.setApiUrl(apiDoc.getString("mapUrl"));
		apiProtalCallAppyEntry.setApiName(apiDoc.getString("configName"));
		apiProtalCallAppyEntry.setApproverUserId("admin");; //指定一个审批者
		apiProtalCallAppyEntry.setAppyUserId(AppContext.getUserId()); //申请者
		apiProtalCallAppyEntry.setStatus(1);//标记为1表示已经审批通过
		apiProtalCallAppyEntry.setRemark(remark);//申请理由
		
		dao.save(apiProtalCallAppyEntry);
		return ViewUtil.getSuccessView("成功申请API的调用权限!");
	}
	
	
}
